import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Button,
  IconButton,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  TextField,
  MenuItem,
  Select,
  FormControl,
  InputLabel,
  Pagination,
  Chip,
  Alert,
  Snackbar,
  CircularProgress
} from '@mui/material';
import {
  Delete as DeleteIcon,
  Edit as EditIcon,
  CheckCircle as ApproveIcon,
  Cancel as RejectIcon,
  Visibility as ViewIcon
} from '@mui/icons-material';
import { ResourceService, Resource, ResourceListResponse } from '../../resources/services/ResourceService';
import { Link } from 'react-router-dom';

const ResourceManagement: React.FC = () => {
  const [resources, setResources] = useState<Resource[]>([]);
  const [allResources, setAllResources] = useState<Resource[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [page, setPage] = useState<number>(1);
  const [totalPages, setTotalPages] = useState<number>(1);
  const [selectedResource, setSelectedResource] = useState<Resource | null>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState<boolean>(false);
  const [rejectDialogOpen, setRejectDialogOpen] = useState<boolean>(false);
  const [rejectReason, setRejectReason] = useState<string>('');
  const [snackbar, setSnackbar] = useState<{open: boolean, message: string, severity: 'success' | 'error'}>({open: false, message: '', severity: 'success'});
  const [filterStatus, setFilterStatus] = useState<string>('all');
  const [searchQuery, setSearchQuery] = useState<string>('');
  const [searchType, setSearchType] = useState<string>('title'); // 'id', 'title', 'uploader'
  const [advancedSearchOpen, setAdvancedSearchOpen] = useState<boolean>(false);
  const [advancedSearchParams, setAdvancedSearchParams] = useState<{
    id: string;
    title: string;
    uploader: string;
  }>({ id: '', title: '', uploader: '' });

  const pageSize = 10;

  // 只保留一个useEffect用于获取资源
  useEffect(() => {
    fetchResources();
  }, [page, filterStatus]);

  // 当搜索查询或搜索类型改变时，执行前端筛选
  useEffect(() => {
    if (allResources.length > 0) {
      filterResources();
    }
  }, [searchQuery, searchType, allResources]);

  const fetchResources = async () => {
    try {
      setLoading(true);
      setError(null);
      
      let status = '';
      if (filterStatus === 'approved') {
        status = 'PASS';
      } else if (filterStatus === 'wait') {
        status = 'WAIT';
      }
      
      // 获取所有资源列表
      const response = await ResourceService.getResourcesByStatus(page, pageSize, status);
      setAllResources(response.records);
      setResources(response.records);
      setTotalPages(Math.ceil(response.total / pageSize));
    } catch (err) {
      setError(err instanceof Error ? err.message : '获取资源列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 前端筛选资源 - 移到组件内部
  const filterResources = () => {
    if (!searchQuery.trim()) {
      // 如果搜索框为空，显示所有资源
      setResources(allResources);
      return;
    }
    
    const query = searchQuery.trim().toLowerCase();
    let filteredResources = [];
    
    switch (searchType) {
      case 'id':
        filteredResources = allResources.filter(resource => 
          resource.id.toString().toLowerCase().includes(query)
        );
        break;
      case 'title':
        filteredResources = allResources.filter(resource => 
          resource.title.toLowerCase().includes(query)
        );
        break;
      case 'uploader':
        filteredResources = allResources.filter(resource => 
          resource.uploaderName.toLowerCase().includes(query)
        );
        break;
      default:
        filteredResources = allResources;
    }
    
    setResources(filteredResources);
  };

  const handlePageChange = (event: React.ChangeEvent<unknown>, value: number) => {
    setPage(value);
  };

  const handleDeleteClick = (resource: Resource) => {
    setSelectedResource(resource);
    setDeleteDialogOpen(true);
  };

  const handleDeleteConfirm = async () => {
    if (!selectedResource) return;
    
    try {
      await ResourceService.deleteResource(selectedResource.id);
      setSnackbar({open: true, message: '资源删除成功', severity: 'success'});
      fetchResources(); // 重新加载资源列表
    } catch (err) {
      setSnackbar({open: true, message: err instanceof Error ? err.message : '删除资源失败', severity: 'error'});
    } finally {
      setDeleteDialogOpen(false);
      setSelectedResource(null);
    }
  };

  const handleApproveResource = async (id: string) => {
    try {
      await ResourceService.reviewResource(id, true);
      setSnackbar({open: true, message: '资源审核通过', severity: 'success'});
      fetchResources(); // 重新加载资源列表
    } catch (err) {
      setSnackbar({open: true, message: err instanceof Error ? err.message : '审核资源失败', severity: 'error'});
    }
  };

  const handleRejectResource = async (id: string) => {
    setSelectedResource(resources.find(r => r.id === id) || null);
    setRejectDialogOpen(true);
  };

  const handleRejectConfirm = async () => {
    if (!selectedResource || !rejectReason) return;
    
    try {
      await ResourceService.reviewResource(selectedResource.id, false, rejectReason);
      setSnackbar({open: true, message: '已拒绝该资源', severity: 'success'});
      fetchResources(); // 重新加载资源列表
    } catch (err) {
      setSnackbar({open: true, message: err instanceof Error ? err.message : '拒绝资源失败', severity: 'error'});
    } finally {
      setRejectDialogOpen(false);
      setSelectedResource(null);
      setRejectReason('');
    }
  };

  const handleSnackbarClose = () => {
    setSnackbar({...snackbar, open: false});
  };

  const handleFilterChange = (event: React.ChangeEvent<{ value: unknown }>) => {
    setFilterStatus(event.target.value as string);
    setPage(1); // 重置到第一页
  };

  const handleSearchChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSearchQuery(event.target.value);
  };

  const handleSearchTypeChange = (event: React.ChangeEvent<{ value: unknown }>) => {
    setSearchType(event.target.value as string);
  };

  const handleAdvancedSearchToggle = () => {
    setAdvancedSearchOpen(!advancedSearchOpen);
  };

  const handleAdvancedSearchParamChange = (param: keyof typeof advancedSearchParams, value: string) => {
    setAdvancedSearchParams(prev => ({
      ...prev,
      [param]: value
    }));
  };

  const handleAdvancedSearch = () => {
    setPage(1); // 重置到第一页
    fetchResources();
  };

  const handleClearAdvancedSearch = () => {
    setAdvancedSearchParams({ id: '', title: '', uploader: '' });
  };

  if (loading && page === 1) {
    return (
      <Box display="flex" justifyContent="center" p={3}>
        <CircularProgress />
      </Box>
    );
  }

  if (error) {
    return <Alert severity="error">{error}</Alert>;
  }

  return (
    <Box>
      <Box sx={{ mb: 3, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Typography variant="h6">资源管理</Typography>
        <Box sx={{ display: 'flex', gap: 2 }}>
          <TextField
            label="搜索资源"
            variant="outlined"
            size="small"
            value={searchQuery}
            onChange={handleSearchChange}
            placeholder="输入关键词进行搜索"
          />
          <FormControl variant="outlined" size="small" sx={{ minWidth: 120 }}>
            <InputLabel id="search-type-label">搜索类型</InputLabel>
            <Select
              labelId="search-type-label"
              value={searchType}
              onChange={handleSearchTypeChange}
              label="搜索类型"
            >
              <MenuItem value="id">ID</MenuItem>
              <MenuItem value="title">标题</MenuItem>
              <MenuItem value="uploader">上传者</MenuItem>
            </Select>
          </FormControl>
          <FormControl variant="outlined" size="small" sx={{ minWidth: 120 }}>
            <InputLabel id="status-filter-label">状态</InputLabel>
            <Select
              labelId="status-filter-label"
              value={filterStatus}
              onChange={handleFilterChange}
              label="状态"
            >
              <MenuItem value="all">全部</MenuItem>
              <MenuItem value="wait">待审核</MenuItem>
              <MenuItem value="approved">已通过</MenuItem>
            </Select>
          </FormControl>
        </Box>
      </Box>

      <TableContainer component={Paper}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>ID</TableCell>
              <TableCell>标题</TableCell>
              <TableCell>上传者</TableCell>
              <TableCell>上传时间</TableCell>
              <TableCell>状态</TableCell>
              <TableCell>操作</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {resources.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} align="center">暂无资源</TableCell>
              </TableRow>
            ) : (
              resources.map((resource) => (
                <TableRow key={resource.id}>
                  <TableCell>{String(resource.id).substring(0, 8)}...</TableCell>
                  <TableCell>{resource.title}</TableCell>
                  <TableCell>{resource.uploaderName}</TableCell>
                  <TableCell>{new Date(resource.uploadTime).toLocaleString('zh-CN')}</TableCell>
                  <TableCell>
                    {resource.reviewStatus === 'PASS' && (
                      <Chip 
                        label="已通过" 
                        color="success" 
                        size="small" 
                        variant="outlined" 
                      />
                    )}
                    {resource.reviewStatus === 'WAIT' && (
                      <Chip 
                        label="待审核" 
                        color="warning" 
                        size="small" 
                        variant="outlined" 
                      />
                    )}
                    {resource.reviewStatus === 'REFUSE' && (
                      <Chip 
                        label="已拒绝" 
                        color="error" 
                        size="small" 
                        variant="outlined" 
                        title={resource.rejectReason}
                      />
                    )}
                    {!resource.reviewStatus && (
                      <Chip 
                        label="待审核" 
                        color="warning" 
                        size="small" 
                        variant="outlined" 
                      />
                    )}
                  </TableCell>
                  <TableCell>
                    {/* 根据状态动态渲染操作按钮 */}
                    <IconButton 
                      size="small" 
                      component={Link} 
                      to={`/resources/${resource.id}`}
                      title="查看"
                    >
                      <ViewIcon fontSize="small" />
                    </IconButton>
                    
                    {/* 待审核状态显示审核按钮 */}
                    {(resource.reviewStatus === 'WAIT' || !resource.reviewStatus) && (
                      <>
                        <IconButton 
                          size="small" 
                          color="primary" 
                          onClick={() => handleApproveResource(resource.id)}
                          title="通过"
                        >
                          <ApproveIcon fontSize="small" />
                        </IconButton>
                        <IconButton 
                          size="small" 
                          color="error" 
                          onClick={() => handleRejectResource(resource.id)}
                          title="拒绝"
                        >
                          <RejectIcon fontSize="small" />
                        </IconButton>
                      </>
                    )}
                    
                    {/* 所有状态都显示删除按钮 */}
                    <IconButton 
                      size="small" 
                      color="error" 
                      onClick={() => handleDeleteClick(resource)}
                      title="删除"
                    >
                      <DeleteIcon fontSize="small" />
                    </IconButton>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </TableContainer>

      <Box sx={{ display: 'flex', justifyContent: 'center', mt: 2 }}>
        <Pagination 
          count={totalPages} 
          page={page} 
          onChange={handlePageChange} 
          color="primary" 
        />
      </Box>

      {/* 删除确认对话框 */}
      <Dialog
        open={deleteDialogOpen}
        onClose={() => setDeleteDialogOpen(false)}
      >
        <DialogTitle>确认删除</DialogTitle>
        <DialogContent>
          <DialogContentText>
            确定要删除资源 "{selectedResource?.title}" 吗？此操作不可撤销。
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteDialogOpen(false)}>取消</Button>
          <Button onClick={handleDeleteConfirm} color="error" autoFocus>
            删除
          </Button>
        </DialogActions>
      </Dialog>

      {/* 拒绝原因对话框 */}
      <Dialog
        open={rejectDialogOpen}
        onClose={() => setRejectDialogOpen(false)}
      >
        <DialogTitle>拒绝资源</DialogTitle>
        <DialogContent>
          <DialogContentText>
            请输入拒绝资源 "{selectedResource?.title}" 的原因：
          </DialogContentText>
          <TextField
            autoFocus
            margin="dense"
            label="拒绝原因"
            type="text"
            fullWidth
            multiline
            rows={4}
            value={rejectReason}
            onChange={(e) => setRejectReason(e.target.value)}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setRejectDialogOpen(false)}>取消</Button>
          <Button onClick={handleRejectConfirm} color="error" autoFocus disabled={!rejectReason.trim()}>
            拒绝
          </Button>
        </DialogActions>
      </Dialog>

      {/* 提示消息 */}
      <Snackbar 
        open={snackbar.open} 
        autoHideDuration={6000} 
        onClose={handleSnackbarClose}
      >
        <Alert 
          onClose={handleSnackbarClose} 
          severity={snackbar.severity} 
          sx={{ width: '100%' }}
        >
          {snackbar.message}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default ResourceManagement;